#include "prs_tcp_server.h"

prs_tcp_server::prs_tcp_server()
{
	addr = {};
	sListen = {};
	Connection = {};
	WSAData wsaData;
	WORD DllVersion = MAKEWORD(2, 1);

	if (WSAStartup(DllVersion, &wsaData) != 0)
	{
		MessageBoxA(NULL, "WinSock startup error", "Error", MB_OK | MB_ICONERROR);
	}
}

prs_tcp_server::~prs_tcp_server()
{
	closesocket(Connection);
	WSACleanup();
}

void prs_tcp_server::begin()
{
	int addrlen = sizeof(addr);
	addr.sin_addr.s_addr = inet_addr(serverIp.c_str()); //target PC
	addr.sin_port = htons(serverPort); // sever Port
	addr.sin_family = AF_INET; //IPv4 Socket

	sListen = socket(AF_INET, SOCK_STREAM, NULL);
	bind(sListen, (SOCKADDR*)&addr, sizeof(addr));
	listen(sListen, SOMAXCONN);

	std::cout << "wait for client to connect..." << std::endl;
	Connection = accept(sListen, (SOCKADDR*)&addr, &addrlen);
	if (Connection == 0)
	{
		std::cout << "bad connection." << std::endl;
	}
	else
	{
		std::cout << "successfully connect a client" << std::endl;
	}
}

void prs_tcp_server::tx(float_t* txd, size_t length)
{
	send(Connection, (char*)txd, (int)sizeof(float_t) * length, NULL);
}

void prs_tcp_server::rx(float_t* rxd, size_t length)
{
	recv(Connection, (char*)rxd, (int)sizeof(float_t) * length, NULL);
}

void prs_tcp_server::tx(double_t* txd, size_t length)
{
	send(Connection, (char*)txd, (int)sizeof(double_t) * length, NULL);
}

void prs_tcp_server::rx(double_t* rxd, size_t length)
{
	recv(Connection, (char*)rxd, (int)sizeof(double_t) * length, NULL);
}